<template>
  <el-drawer
    v-model="showDrawer"
    :title="$t('发送')"
    size="35%"
    @close="emit('close')"
  >
    <el-card>
      <el-form
        ref="sendFormRef"
        label-position="top"
        :model="sendForm"
        :rules="rules"
      >
        <el-form-item :label="$t('币种')" prop="coinName">
          <el-select
            style="width: 100%"
            v-model="sendForm.coinName"
            :placeholder="$t('请选择币种')"
            @change="changeCoin"
          >
            <el-option
              v-for="item in coins"
              :key="item.coin_name"
              :label="item.coin_name"
              :value="item.coin_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="sonCoins?.length" prop="sonCoinsName">
          <el-radio-group
            v-model="sendForm.sonCoinsName"
            @change="changeSonCoin"
          >
            <el-radio-button v-for="item in sonCoins" :label="item.chain_name"
              >{{ item.chain_alias }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item :label="$t('地址类型')" prop="addrType">
          <el-select
            style="width: 100%"
            v-model="sendForm.addrType"
            :placeholder="$t('请选择地址类型')"
            @change="changeAddressType"
          >
            <el-option
              v-for="item in addressTypes"
              :key="item.key"
              :label="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('发送至')" prop="address">
          <el-input
            v-model="sendForm.address"
            :placeholder="$t('请输入地址')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('发送金额')" prop="amount">
          <el-input
            v-model="sendForm.amount"
            type="number"
            :placeholder="$t('请输入金额')"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%; text-align: right">
            {{ $t("手续费") }} {{ feeAmount }} {{ feeInfo.fee_unit }}
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <p class="mt-2 text-[#7F7F7F] text-sm">
      <span class="text-[#e54c5f] mr-2" v-if="feeInfo.tips">*</span
      >{{ feeInfo.tips }}
    </p>
    <div class="submitBtnCont">
      <el-button
        style="width: 50%"
        size="large"
        type="primary"
        @click="submitForm(sendFormRef)"
      >
        {{ $t("下一步") }}
      </el-button>
    </div>

    <el-drawer v-model="showSonDrawer" :title="$t('确认订单')" size="35%">
      <el-card>
        <div class="confirmCoinRow">
          <span class="rowName">{{ $t("交易类型") }}</span>
          <span class="rowValue">{{ $t("发送") }}</span>
        </div>
        <!-- <div class="confirmCoinRow">
          <span class="rowName">{{ $t("地址类型") }}</span>
          <span class="rowValue">{{ sendForm.addrType }}</span>
        </div> -->
        <div class="confirmCoinRow">
          <span class="rowName">{{ $t("接收地址") }}</span>
          <span class="rowValue">{{ sendForm.address }}</span>
        </div>
        <div class="confirmCoinRow">
          <span class="rowName">{{ $t("发送数量") }}</span>
          <span class="rowValue">{{ sendForm.amount }}</span>
        </div>
        <div class="confirmCoinRow">
          <span class="rowName">{{ $t("手续费") }}</span>
          <span class="rowValue">{{ feeAmount }} {{ feeInfo.fee_unit }}</span>
        </div>

        <el-card>
          <el-form
            ref="sendFormRef1"
            label-position="top"
            :model="sendForm1"
            :rules="rules1"
          >
            <el-form-item
              :label="$t('交易密码')"
              prop="password"
              show-password
              style="position: relative"
            >
              <!-- 判断是否已经设置支付密码了，若没有则显示设置按钮 -->
              <el-button
                v-show="!isHasPayPwd"
                class="setBtn"
                size="small"
                text
                type="primary"
                @click="showSetPayPwdDrawer"
                >{{ $t("设置") }}</el-button
              >
              <el-input
                v-model="sendForm1.password"
                :placeholder="$t('请输入支付密码')"
                type="password"
                show-password
              >
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="isVAlid"
              :label="$t('谷歌验证')"
              prop="google_code"
            >
              <el-input
                v-model="sendForm1.google_code"
                :placeholder="$t('请输入6位谷歌验证码')"
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-form>
        </el-card>

        <el-button
          style="width: 100%"
          size="large"
          type="primary"
          @click="confirmForm(sendFormRef1)"
        >
          {{ $t("提交") }}
        </el-button>
      </el-card>
    </el-drawer>
  </el-drawer>

  <setPayPasswordDrawer
    :show="isShowPayPwdDrawer"
    codeType="set"
    @close="closePayPwdDrawer"
  />
</template>
<script setup>
import { ref, reactive, watch, onMounted, computed } from "vue";
import { useMerchantStore } from "@/store/modules/merchant";
import { useUserStore } from "@/store/modules/user";
import { postWalletSendNewApi, getWalletSendNewApi } from "@/api/wallet/index";
import setPayPasswordDrawer from "../../settings/components/setPayPasswordDrawer.vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import _ from "lodash";
const merchantStore = useMerchantStore();
const isHasPayPwd = ref(false);
const useUser = useUserStore();
const coins = computed(() => {
  return useUser.currentCoinListInfo.value;
});

onMounted(async () => {
  await merchantStore.getMerchantInfo();
  //   判断是否有谷歌验证
  if (merchantStore.merchantInfo.is_google_auth_open > 0) {
    isVAlid.value = true;
  } else {
    isVAlid.value = false;
  }
});

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  currentCoinInfo: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["close"]);
const showDrawer = ref(false);
const showSonDrawer = ref(false);
const feeInfo = reactive({
  fee: 0,
  fee_unit: "",
  tips: "",
});

watch(
  () => props.show,
  (newVal) => {
    showDrawer.value = newVal;
    if (newVal) {
      isHasPayPwd.value = merchantStore.merchantInfo.is_trade_pwd;
      // getFeeInfo();
    }
  }
);
//监听传输进来的数据
watch(
  () => props.currentCoinInfo,
  (newVal) => {
    if (Object.keys(newVal).length > 0) {
      const index = coins.value.findIndex(
        (i) => i.coin_name === newVal.coin_name
      );
      if (index > -1) {
        sendForm.coinName = coins.value[index].coin_name;
        sonCoins.value = coins.value[index].chains;
        sendForm.sonCoinsName = sonCoins.value[0].chain_name;

        // getFeeInfo();
      }

      return;
    }
    // setCoinInfo(0);
  },
  { immediate: true, deep: true }
);

const feeAmount = computed(() => {
  return sendForm.amount
    ? Number(feeInfo.fee) + Number(sendForm.amount) * Number(feeInfo.fee_rate)
    : 0;
});

const sonCoins = ref([]);
const addressTypes = ref([
  { key: "email", value: t("邮箱") },
  { key: "address", value: t("地址") },
]);

const sendFormRef = ref();
const sendFormRef1 = ref();
const sendForm = reactive({
  coinName: "",
  sonCoinsName: "",
  addrType: "",
  address: "",
  amount: "",
});
const sendForm1 = reactive({
  password: "",
  google_code: "",
});
const checkAmount = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t("请输入金额")));
  } else if (
    Number(value) >
    Number(
      coins.value.find((x) => x.coin_name === sendForm.coinName)?.available
    )
  ) {
    callback(new Error(t("您当前币种的可用余额不足！")));
  } else {
    callback();
  }
};
const rules = reactive({
  coinName: [{ required: true, message: t("请选择币种"), trigger: "blur" }],
  addrType: [{ required: true, message: t("请选择地址类型"), trigger: "blur" }],
  address: [{ required: true, message: t("请输入地址"), trigger: "blur" }],
  amount: [{ required: true, validator: checkAmount, trigger: "blur" }],
});
const rules1 = reactive({
  password: [{ required: true, message: t("请输入支付密码"), trigger: "blur" }],
  google_code: [
    { required: true, message: t("请输入6位谷歌验证码"), trigger: "blur" },
  ],
});

//修改币种时触发
const changeCoin = (e) => {
  sonCoins.value = coins.value.find((x) => x.coin_name === e).chains;
  sendForm.sonCoinsName = sonCoins.value[0].chain_name;

  getFeeInfo();
};

// 修改链的时候触发
const changeSonCoin = async (e) => {
  sendForm.sonCoinsName = e;
  getFeeInfo();
};

// 修改地址类型的时候触发
const changeAddressType = (e) => {
  sendForm.addrType = e;
};

//获取手续费
const getFeeInfo = async (e) => {
  try {
    const res = await getWalletSendNewApi({
      coin_name: sendForm.coinName,
      chain_name: sendForm.sonCoinsName,
    });

    feeInfo.fee = res.fee;
    feeInfo.fee_unit = res.fee_unit;
    feeInfo.fee_rate = res.fee_rate;
    feeInfo.tips = res.tips;
  } catch (e) {
    console.log(e);
    return false;
  }
};

// 验证表单，验证通过后显示确认订单弹窗
const submitForm = (formRef) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      //打开确认弹窗
      showSonDrawer.value = !showSonDrawer.value;
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 计算发送订单接口所传的参数
const form = computed(() => {
  return {
    coin_name: sendForm.coinName,
    chain_name: sendForm.sonCoinsName,
    // send_type: addressTypes.value.find((i) => i.value === sendForm.addrType)
    //   .key,
    address: sendForm.address,
    amount: sendForm.amount,
    trade_pwd: sendForm1.password,
  };
});

const isVAlid = ref(false);
// 确认订单
const confirmForm = async (formRef) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      try {
        let params = { ...form.value };
        if (isVAlid.value) {
          params.google_code = sendForm1.google_code;
        }
        console.log(params, "params");
        const { bill_no } = await postWalletSendNewApi(params);
        if (bill_no) {
          //关闭当前所有弹窗并打开详情弹窗
          emit("close", bill_no);
          showSonDrawer.value = false;
          for (const item in sendForm) {
            sendForm[item] = "";
          }
          sonCoins.value = [];
        }
      } catch (e) {
        console.log(e);
        return false;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 控制设置支付密码弹窗
const isShowPayPwdDrawer = ref(false);
const showSetPayPwdDrawer = () => {
  isShowPayPwdDrawer.value = !isShowPayPwdDrawer.value;
};
const closePayPwdDrawer = async () => {
  isHasPayPwd.value = true;
  await merchantStore.getMerchantInfo();
  isShowPayPwdDrawer.value = false;
};
</script>
<style lang="scss">
.submitBtnCont {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  width: 100%;
}

.setBtn {
  position: absolute;
  top: 0%;
  right: 0%;
  transform: translate(0, -130%);
}

.confirmCoinRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.25rem;
  .rowName {
    width: 30%;
    flex-shrink: 0;
  }
  .rowValue {
    width: 50%;
    text-align: right;
    word-break: break-all;
  }
}
</style>
